package fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.cyan.tools.base.RecyclerArrayAdapter;
import com.cyan.tools.util.RxBus;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import java.io.IOException;
import java.util.ArrayList;

import adapter.NewsListAdapter;
import app.AutoFragment;
import application.AppApplication;
import bean.NewsItem;
import bean.Result;
import menhoo.com.i8officelibrary.R;
import model.TabModel;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import view.recyclerview.HeaderAndFooterWrapper;

public class NewsListFragment extends Fragment implements TextView.OnEditorActionListener {
    RecyclerView recyclerView;
    SwipeRefreshLayout refreshLayout;
    TextView empty;
    TextView error;
    public boolean is_first = true;
    private NewsListAdapter adapter;
    private HeaderAndFooterWrapper wadapter;
    private int pageNumber = 0, pageSize = 10;
    private TextView tvCount;
    private String url;
    private TextView tvTitle;
    private EditText mKeyWord;
    private String keyword = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news_list, null);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        url = getArguments().getString("Url");
        String title = getArguments().getString("Title");
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        refreshLayout.setRefreshing(true);
        getData();
    }


    protected void initView(View rootView) {
        rootView.findViewById(R.id.frame_ui_btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        mKeyWord = rootView.findViewById(R.id.keyword);
        mKeyWord.setOnEditorActionListener(this);
        tvTitle = rootView.findViewById(R.id.title);
        recyclerView = rootView.findViewById(R.id.list);
        refreshLayout = rootView.findViewById(R.id.refresh_layout);
        empty = rootView.findViewById(R.id.empty);
        error = rootView.findViewById(R.id.error);
        adapter = new NewsListAdapter(getActivity());
        wadapter = new HeaderAndFooterWrapper(adapter);
        View header = LayoutInflater.from(getContext()).inflate(R.layout.news_header, null);
        header.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tvCount = header.findViewById(R.id.count);
        wadapter.addHeaderView(header);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(wadapter);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.tab_top_bg));
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNumber = 0;
                getData();
            }
        });
    }

    private void getData() {
        OkHttpClient client = new OkHttpClient();
        String urlF = url + "&__session__=" + AppApplication.getSession() + "&pageIndex=" + pageNumber + "&pageSize=" + pageSize + "&keyword=" + keyword;
        KLog.e("urlF:" + urlF);
        Request request = new Request.Builder()
                .url(urlF)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                HandlerUtil.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                });
                try {
                    String result = response.body().string();
                    KLog.e("result:" + result);
                    final Result<ArrayList<NewsItem>> data = new Gson().fromJson(result, new TypeToken<Result<ArrayList<NewsItem>>>() {
                    }.getType());
                    HandlerUtil.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvCount.setText("记录总数：" + data.getTotalCount());
                            showResult(data.getData());
                        }
                    });
                } catch (Exception e) {
                    KLog.e("出错了" + e.toString());
                }
            }
        });
    }

    public void toast(String msg) {

    }

    public void showResult(final ArrayList<NewsItem> data) {
        if (is_first) {
            adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    NewsItem item = adapter.getItem(position - 1);
//                    TabModel model = new TabModel();
//                    model.code = "newsweb";
//                    model.type = "newsweb";
//                    model.name = item.Title;
//                    model.htmlUrl = item.Url;
                    Intent it = new Intent("com.i8office.android.zhihuixinwu.ui.NewsDetailActivity");
                    it.putExtra("item", item);
                    startActivity(it);
                }
            });
            adapter.setMore(R.layout.view_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    pageNumber += 1;
                    getData();
                    if (adapter.getCount() % pageSize != 0) {
                        adapter.stopMore();
                    }
                }
            });
            adapter.setError(R.layout.view_more_error).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    adapter.resumeMore();
                }
            });
            adapter.setNoMore(R.layout.view_nomore);
            is_first = false;
        }
        if (pageNumber == 0) {
            adapter.clear();
        }
        recyclerView.setVisibility(View.VISIBLE);
        empty.setVisibility(View.GONE);
        error.setVisibility(View.GONE);
        adapter.addAll(data);
        wadapter.notifyDataSetChanged();
    }

    public void showUnReadNum(int num) {
        if (getArguments().getBoolean("isNotify", false)) {
            RxBus.get().post("OnGetMsgNum", num);
        }
    }

    public void showEmpty() {
        refreshLayout.setRefreshing(false);
        if (adapter.getCount() == 0) {
            adapter.clear();
            empty.setVisibility(View.VISIBLE);
        } else adapter.stopMore();
    }

    public void showError() {
        refreshLayout.setRefreshing(false);
        if (adapter.getCount() == 0) {
            adapter.clear();
            error.setVisibility(View.VISIBLE);
        } else adapter.pauseMore();
    }

    public void showProgress() {
        if (is_first) {
            error.setVisibility(View.GONE);
            empty.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
        }
    }

    public void hideProgress() {
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("is_first", is_first);
        outState.putInt("pageNumber", pageNumber);
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {
            is_first = savedInstanceState.getBoolean("is_first");
            pageSize = savedInstanceState.getInt("pageNumber");
        }
    }

    public void onViewClicked() {
        getData();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            IMEHelper.hideIME(getActivity(), true);
            keyword = mKeyWord.getText().toString().trim();
            pageNumber = 0;
            getData();
            return true;
        }
        return false;
    }
}
